package com.zros.modules.business.controller;


import io.swagger.annotations.ApiOperation;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zros.common.api.vo.PageResult;
import com.zros.common.api.vo.Result;
import com.zros.common.api.vo.Select;
import com.zros.common.exception.JeecgBootException;
import com.zros.modules.business.dto.CreateTeacherDto;
import com.zros.modules.business.dto.QueryTeacherDto;
import com.zros.modules.business.dto.UpdateTeacherDto;
import com.zros.modules.business.entity.Audition;
import com.zros.modules.business.service.IAuditionService;
import com.zros.modules.business.service.ISelectService;
import com.zros.modules.business.service.ITeacherService;
import com.zros.modules.business.vo.OrgTeaInfoVo;
import com.zros.modules.business.vo.TeacherInfoVo;
import com.zros.modules.shiro.authc.util.JwtUtil;
import com.zros.modules.system.dto.UserInfo;
import com.zros.modules.system.service.IUserService;

/**
 * <p>
 * 教师表 前端控制器
 * </p>
 *
 * @author pangyinqiango
 * @since 2019-04-16
 */
@RestController
@RequestMapping("/business/teacher")
@PropertySource("classpath:config.properties")
public class TeacherController {
	
	@Value("${authority.campusKey}")
	private String authorityCampusKey;
	
	@Value("${org.campusKey}")
	private String campusKey;
	
	@Autowired
	private IUserService userService;
	
	@Autowired
	private ISelectService selectService;
	
	@Autowired
	private ITeacherService teacherService;
	
	@Autowired
	private IAuditionService auditionService;
	
	/**
	 * 分页查询老师
	 */
	@ApiOperation(value = "分页查询老师")
	@RequiresPermissions("business:teacher:list")
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public PageResult<TeacherInfoVo> queryPageList(HttpServletRequest request, Page<TeacherInfoVo> page, QueryTeacherDto queryTeacherDto) 
	{
		//获取当前用户
		UserInfo currentUser = queryCurrentUser(request,"queryTeacher");
		//获取数据权限key
		String dataResourceKey = currentUser.getDataResourceKey();
		if(StringUtils.isEmpty(dataResourceKey))
		{
			throw new JeecgBootException("数据权限查询不到！请联系管理员！");
		}
		
		//校区权限，查询自己所属校区渠道类型
		if(authorityCampusKey.equals(dataResourceKey))
		{
			queryTeacherDto.setUserId(currentUser.getId());
		}
		
		
		IPage<TeacherInfoVo> pageTeacher = teacherService.selectTeacherList(page, queryTeacherDto);
		//拼组织名称
		Map<String, String> selectMap = new HashMap<String, String>();
		selectMap.put("campusKey", campusKey);
		List<Select> orgSelectList = selectService.queryOrgSelect(selectMap);
		selectMap.clear();
		for(Select select : orgSelectList)
		{
			selectMap.put(select.getValue(), select.getLabel());
		}
		
		for(TeacherInfoVo teacherInfoVo : pageTeacher.getRecords())
		{
			String orgName = "";
			for(OrgTeaInfoVo orgTeaInfoVo : teacherInfoVo.getOrgTeaList())
			{
				orgName += selectMap.get(orgTeaInfoVo.getOrganizationId()) + " " ;
			}
			teacherInfoVo.setOrganizationName(orgName);
		}
		
        PageResult<TeacherInfoVo> pageResult = new PageResult<TeacherInfoVo>(pageTeacher.getRecords().size(), pageTeacher.getRecords());
        return pageResult;
	}
	
	/**
	 * 添加老师
	 */
	@ApiOperation(value = "添加老师")
	@RequiresPermissions("business:teacher:list")
	@PostMapping("/create")
	public Result<?> create(@RequestBody CreateTeacherDto teacher) 
	{
        if (teacherService.onlyCheck(teacher)) {
            throw new JeecgBootException("老师名称在该校区中已经存在！");
        }
		
		return new Result<>().success(teacherService.createTeacher(teacher) ? "添加成功" : "添加失败，请重试");
	}

	/**
	 * 修改老师
	 */
	@ApiOperation(value = "修改老师")
	@RequiresPermissions("business:teacher:list")
	@PostMapping("/update")
	public Result<?> update(@RequestBody UpdateTeacherDto teacher) 
	{
		if (teacherService.onlyCheck(teacher)) {
            throw new JeecgBootException("老师名称在该校区中已经存在！");
        }
		
		return new Result<>().success(teacherService.updateTeacher(teacher) ? "修改成功" : "修改失败，请重试");
	}
	/**
	 * 删除老师
	 */
	@ApiOperation(value = "删除老师")
	@RequiresPermissions("business:teacher:list")
	@PostMapping("/delete/{id}")
	public Result<?> delete(@PathVariable("id") Long id) 
	{
		if (null == id) {
			return new Result<>().error("ID不能为空");
		}
		
		//试听课程
		QueryWrapper<Audition> ew = new QueryWrapper<>();
		ew.eq("teacher_id", id);
		List<Audition> auditionList = auditionService.list(ew);
		if (!CollectionUtils.isEmpty(auditionList)) {
			throw new JeecgBootException("该老师已有试听课记录，不可删除！");
		}
		
		return new Result<>().success(teacherService.removeById(id) ? "删除成功" : "删除失败，请重试");
	}
	
	/**
	 *  获取当前用户
	 */
	UserInfo queryCurrentUser(HttpServletRequest request,String queryMethod)
	{
		UserInfo currentUser = new UserInfo();
		String userAccount = JwtUtil.getUserAccountByToken(request);
		currentUser = userService.queryUserInfoByAccount(userAccount,queryMethod);
		
		return currentUser;
	}
}
